/**
 * Created by Mars on 2015/11/18.
 */
app.config(function ($routeProvider, $locationProvider) {
    $routeProvider.
    when('/map', {
        templateUrl: 'map/index.html',
        controller: 'mapController'
    }).
    when('/map/company/:companyCode', {
        templateUrl: 'map/index.html',
        controller: 'mapController'
    });
});

function mapService() {
    return {
        map: '',
        minZoom: '2',
        maxZoom: '20',
        mgr: '',
        init: function (domId) {
            this.map = new BMap.Map(domId);

            var point = new BMap.Point(120.381163, 36.093801);
            this.map.centerAndZoom(point, 14);
            this.map.enableScrollWheelZoom();

            this.mgr = new BMapLib.MarkerManager(this.map, {borderPadding: 200, maxZoom: 20, trackMarkers: false});

            return this.map;
        },
        markers: function (point, data, fn) {
            var position = point;
            var msg = data;
            var markers = [];
            var realBounds = this.mgr._getRealBounds();

            for (var i = 0; i < position.length; i++) {
                var point = new BMap.Point(position[i].lng, position[i].lat);
                var marker = new BMap.Marker(point);
                markers.push({
                    point: point,
                    marker: marker,
                    title: msg['title'],
                    info: msg['info']
                });
                this.mgr.addMarker(marker, this.minZoom, this.maxZoom);
                var iconSize = new BMap.Size(48, 48);
                var myIcon = new BMap.Icon(msg['markerIcon'], iconSize);
                myIcon.setImageSize(iconSize);
                marker.setIcon(myIcon);
                marker.disableDragging();
            }

            var mks = this.clickMarkers(markers, msg, fn);
            this.mgr.showMarkers();
            return mks;
        },
        clickMarkers: function (markers, msg, fn) {
            var thisMap = this.map;
            var thisMgr = this.mgr;
            for (var i = 0; i < markers.length; i++) {
                markers[i].marker.addEventListener("click", function () {
                    thisMap.panTo(this.point);
                    var opts = {
                        width: 250,     // 信息窗口宽度
                        height: 120,     // 信息窗口高度
                        title: msg['title']  // 信息窗口标题
                    };
                    var infoWindow = new BMap.InfoWindow(msg['info'], opts);  // 创建信息窗口对象
                    thisMap.openInfoWindow(infoWindow, this.point);      // 打开信息窗口
                });
                (function (mk, n) {
                    mk.addEventListener("dblclick", function () {
                        if (n == 0) { //删掉为0的marker ， 会出现bug， 暂时保留
                            return;
                        }
                        thisMgr.removeMarker(mk);      // 打开信息窗口
                    });
                })(markers[i].marker, i)
            }
            if (typeof fn === 'function') {
                fn();
            }
            return markers;
        },
        clearMarkers: function () {
            this.mgr.clearMarkers();
        },
        closeInfoWindow: function () {
            this.map.closeInfoWindow();
        },
        createPoint: function (lng, lat) {
            if (typeof lng === 'number' && typeof lat === 'number') {
                return new BMap.Point(lng, lat);
            } else {
                return new BMap.Point(0, 0);
            }
        }
    };
}

function signService($http) {
    return {
        signIn: function (data, fn) {
            var servantId = typeof data.servant_id === 'undefined' || !data.servant_id ? '' : data.servant_id;
            var param = {
                order_id: typeof data.order_id === 'undefined' || !data.order_id ? '' : data.order_id,
                longitude: typeof data.longitude === 'undefined' || !data.longitude ? '' : data.longitude,
                latitude: typeof data.latitude === 'undefined' || !data.latitude ? '' : data.latitude,
                type: '签到',
                description: typeof data.description === 'undefined' || !data.description ? '' : data.description,
                attribute: typeof data.attribute === 'undefined' ? {} : data.attribute
            };
            baas_yl.call({
                http: $http,
                method: 'post',
                uri: 'servant/servant/signin/' + servantId,
                data: param,
                success: function (json) {
                    if (typeof fn === 'function') {
                        fn(json);
                    }
                }
            });
        },
        signOut: function (data, fn) {
            var servantId = typeof data.servant_id === 'undefined' || !data.servant_id ? '' : data.servant_id;
            var signId = typeof data.sign_id === 'undefined' || !data.sign_id ? '' : data.sign_id;
            var param = {
                type: '签出',
                description: typeof data.description === 'undefined' || !data.description ? '' : data.description
            };
            baas_yl.call({
                http: $http,
                method: 'post',
                uri: 'servant/servant/signout/' + signId + '/' + servantId,
                data: param,
                success: function (json) {
                    if (typeof fn === 'function') {
                        fn(json);
                    }
                }
            });
        },
        listSignItem: function (data, fn) {
            var param = data;
            /*var param = {
             servant_id: typeof data.servant_id === 'undefined' || !data.servant_id ? '' : data.servant_id,
             order_id: typeof data.order_id === 'undefined' || !data.order_id ? '' : data.order_id,
             servant_name: typeof data.servant_name === 'undefined' || !data.servant_name ? '' : data.servant_name,
             type: typeof data.type === 'undefined' || (data.type !== '签到' && data.type !== '签出') ? '' : data.type,
             status: typeof data.status === 'undefined' || !data.status ? '' : data.status,
             start_time: typeof data.start_time === 'undefined' || !data.start_time ? '' : data.start_time,
             end_time: typeof data.end_time === 'undefined' || !data.end_time ? '' : data.end_time
             };*/
            baas_yl.call({
                http: $http,
                method: 'get',
                uri: 'servant/servant/sign/list',
                data: param,
                success: function (json) {
                    if (typeof fn === 'function') {
                        fn(json);
                    }
                }
            });
        },
        deleteSignItem: function (data, fn) {
            var signId = typeof data.sign_id === 'undefined' || !data.sign_id ? '' : data.sign_id;
            baas_yl.call({
                http: $http,
                method: 'get',
                uri: 'servant/servant/sign/delete/' + signId,
                success: function (json) {
                    if (typeof fn === 'function') {
                        fn(json);
                    }
                }
            });
        }
    };
}

app.factory('mapService', mapService);
app.factory('signService', signService);
app.controller('mapController', ['$scope', '$rootScope', '$routeParams', '$http', '$window', '$location', '$interval', 'mapService', 'signService', 'servantService', 'companyService', mapController]);

function mapController($scope, $rootScope, $routeParams, $http, $window, $location, $interval, mapService, signService, servantService, companyService) {
    $scope.appID = $routeParams.app_id;
    $scope.baseURL = $location.$$protocol + '://' + $location.$$host + '/shuangqian';
    $scope.manager = JSON.parse(localStorage.getItem(sessionStorage.getItem("who") + "manager"));

    mapService.init("l-map");

    $scope.getList = function (fn, opt) {
        var param = {};
        if (typeof opt.isOnlyToday === 'boolean' && opt.isOnlyToday) {
            var baseDate = new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate();
            param.start_time = baseDate + ' 00:00:00';
            param.end_time = baseDate + ' 23:59:59';
        }
        if (typeof opt.companyCode === 'string' && opt.companyCode) {
            param.company_code = opt.companyCode;
        }
        signService.listSignItem(param, function (json) {
            if (json.count) {
                var srcList = json.list;
                var destList = [];
                for (var i = 0; i < srcList.length; i++) {
                    if (srcList[i].type === '签到'
                        && typeof srcList[i].longitude !== 'undefined' && srcList[i].longitude
                        && typeof srcList[i].latitude !== 'undefined' && srcList[i].latitude) {
                        var tmp = srcList[i];
                        if (destList.length) {
                            var mark = false;
                            for (var j = 0; j < destList.length; j++) {
                                if (tmp.servant_id === destList[j].servant_id) {
                                    mark = true;
                                }
                            }
                            if (!mark) {
                                destList.push(tmp);
                            }
                        } else {
                            destList.push(tmp);
                        }
                    }
                }
                if (typeof fn === 'function') {
                    fn(destList);
                }
            }
        });
    };

    $scope.setMarkers = function (list) {
        for (var i = 0, len = list.length; i < len; i++) {
            $scope.setMarker(list[i]);
        }
    };

    $scope.setMarker = function (item) {
        servantService.find_one(item.servant_id, $scope.appID, function (json) {
            if (json.status) {
                var servant = json.servant;
                var servantPhoto = typeof servant.photo === 'string' && servant.photo ?
                WEB_URL + servant.photo : $scope.baseURL + '/public/img/noimg.jpeg';
                var data = {
                    title: '<div class="pop-title">'
                    + servant.name
                    + '</div>',
                    info: '<div class="pop-content">'
                    + '<div class="pop-photo"><img src="' + servantPhoto + '"></div>'
                    + '<div class="pop-info">'
                    + '<p>所属企业：' + servant.company_name + '</p>'
                    + '<p>在岗状态：' + servant.servantstatus + '</p>'
                    + '<p><a onclick="openSeviceRecordWindow(&quot;'
                    + servant._id.$id + '&quot;)">服务记录</a></p>'
                    + '</div></div>',
                    markerIcon: servantPhoto
                };
                var point = mapService.createPoint(+item.longitude, +item.latitude);
                mapService.markers([point], data);
            }
        });
    };

    $scope.listRecord = function () {
        var param = {
            isOnlyToday: false,
            companyCode: typeof $scope.companyCode === 'undefined' || !$scope.companyCode ? '' : $scope.companyCode
        };
        $scope.getList(function (list) {
            $scope.setMarkers(list);
        }, param);
    };

    $scope.setCompany = function (item) {
        var company = item;
        console.log(company);
        var companyPhoto = $scope.baseURL + '/public/img/fuwuzhan.png';
        var data = {
            title: '<div class="pop-title">'
            + company.name
            + '</div>',
            info: '<div class="pop-content">'
            + '<div class="pop-photo"><img src="' + companyPhoto + '"></div>'
            + '<div class="pop-info">'
            + '<p>公司地址：' + company.address + '</p>'
            + '<p>联系电话：' + company.telephone + '</p>'
            + '<p><a href="'
            + '#/map/company/' + company.code + '">查看公司</a></p>'
            + '</div></div>',
            markerIcon: companyPhoto
        };
        var point = mapService.createPoint(+company.longitude, +company.latitude);
        mapService.markers([point], data);
    };

    $scope.setCompanies = function () {
        companyService.listAllCompanies(function (json) {
            var list = json.list;
            for (var i = 0, len = list.length; i < len; i++) {
                if (typeof list[i].code === 'undefined'
                    || typeof list[i].longitude === 'undefined'
                    || typeof list[i].latitude === 'undefined'
                    || !list[i].code
                    || !list[i].longitude
                    || !list[i].latitude) {
                    continue;
                }
                $scope.setCompany(list[i]);
            }
        });
    };

    $scope.checkAccount = function () {
        if (typeof $scope.manager.type_code === 'undefined') {
            return;
        }
        if ($scope.manager.type_code === 'admin'
            && typeof $routeParams.companyCode !== 'undefined') {
            $scope.companyCode = $routeParams.companyCode;
        } else if ($scope.manager.type_code === 'admin'
            && typeof $routeParams.companyCode === 'undefined') {
            $scope.setCompanies();
            return;
        } else if ($scope.manager.type_code === 'company'
            && typeof $scope.manager.company_code !== 'undefined'
            && typeof $routeParams.companyCode !== 'undefined'
            && $scope.manager.company_code !== $routeParams.companyCode) {
            alert('无法查看其他服务站信息！');
            return;
        } else if ($scope.manager.type_code === 'company'
            && typeof $scope.manager.company_code !== 'undefined'
            && typeof $routeParams.companyCode === 'undefined') {
            $scope.companyCode = $scope.manager.company_code;
        } else {
            return;
        }
        $scope.listRecord();
        var interval = $interval($scope.listRecord, 5000);
        $rootScope.$on('$routeChangeSuccess', function () {
            $interval.cancel(interval);
        });
    };
    $scope.checkAccount();
}